package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * <ul>成都数城科技有限公司
 * <li>Author: 		chs</li>
 * <li>E-Mail:		935369680@qq.com</li>
 * <li>Date: 		 @Date 2024/3/13 10:48 </li>
 * <li>Description:	 </li>
 * <li>+-History-------------------------------------+</li>getDictionary
 * <li>| Date		     Author		Description	</li>
 * <li>| @Date 2024/3/13 10:48         chs       Created   </li>
 * <li>+------------------------------------------------</li>
 * </ul>
 *
 * @author chs
 */
public class SimpleReidLock implements Ilock {
    //    锁名称
    private String name;
    //    redis调用模板
    private StringRedisTemplate stringRedisTemplate;
    //    key前缀
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PERFIX = UUID.randomUUID(true) + "-";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    //这是静态代码块，在类加载时会执行。
    static {
//        创建资源加载器
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
//         ClassPathResource 表示 resource的路径
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
//        设置返回值类型
        UNLOCK_SCRIPT.setResultType(Long.class);

    }

    /**
     * @param name                key名称
     * @param stringRedisTemplate redis模板对象
     * @Title: SimpleReidLock
     * @Description
     * @Author chs
     * @Date 2024/3/13 11:35
     * @Return
     * @Throws
     **/

    public SimpleReidLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
//        获取线程标识
        String threadId = ID_PERFIX + Thread.currentThread().getId();

        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS));
    }

    /**
     * 重写释放锁逻辑达成 判断锁与释放锁逻辑执行的原子性
     */
    @Override
    public void unLock() {
//   基于lua脚本实现删除锁
//        Collections.singletonList 生成单元素集合
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + name),ID_PERFIX+Thread.currentThread().getId());


    }

//    @Override
//    public void unLock() {
////        获取线程标识
//        String threadId = ID_PERFIX+Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        if(threadId.equals(id)){
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }
//
//    }
}
